package com.dzm.demo.myshop.web.admin.abstracts;

import com.dzm.demo.myshop.commons.dto.BaseResult;
import com.dzm.demo.myshop.commons.persistence.BaseTreeEntity;
import com.dzm.demo.myshop.commons.persistence.BaseTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

public abstract class AbstractsBaseTreeController<T extends BaseTreeEntity,S extends BaseTreeService<T>>{

    @Autowired
    protected S service;

    /**
     * 跳转列表页
     * @return
     */
    public abstract String list(Model model);

    /**
     * 跳转用户表单页
     * @return
     */
    public abstract String form(T t);

    /**
     * 保存信息
     * @param t
     * @param model
     * @param redirectAttributes
     * @return
     */
    public abstract String save(T t, Model model, RedirectAttributes redirectAttributes);

    /**
     * 删除
     * @param ids
     * @return
     */
    public abstract BaseResult delete(String ids);

    /**
     * 树形结构
     *
     * @param id
     * @return
     */
    public abstract List<T> treeData(Long id);

    /**
     * 排序
     * @param sourceList 数据源集合
     * @param targetList 排序后集合
     * @param parentId 父节点ID
     */
    protected void sortList(List<T> sourceList,List<T> targetList,Long parentId){
        for (T sourceEntity : sourceList) {
            if(sourceEntity.getParent().getId().equals(parentId)){
                targetList.add(sourceEntity);

                //判断是否有子节点
                if(sourceEntity.getIsParent()){
                    for (T currentEntity : sourceList) {
                        if (currentEntity.getParent().getId().equals(sourceEntity.getId())){
                            sortList(sourceList,targetList,sourceEntity.getId());
                            break;
                        }
                    }
                }
            }
        }
    }

}
